<?php
/*
    Copyright (C) 2008 - 2010 Inanta Martsanto
    
    This file is part of Koma.

    Koma is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Koma is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Koma.  If not, see <http://www.gnu.org/licenses/>.
    
    Inanta Martsanto (inanta@inationsoft.com)
*/

if(!defined('KOMA_MAINFILE_INCLUDED')) exit ('Exit');

final class KomaAuthentication extends KomaSingletonObject
{   
    function login($username = '', $password = '')
    {
        global $komaDB;
        
        if($username == '' || $password == '')
        {
            return false;
        }
        
        $result	= $komaDB->query("
                                 SELECT u.uid, u.username, u.password, r.rid
                                 FROM ".$komaDB->prefix('users')." u, ".$komaDB->prefix('roles_users_link')." r
                                 WHERE u.username = '".$username."' AND u.password ='".md5($password)."' AND r.uid = u.uid");
        
        if($komaDB->numRows($result) > 0)
        {
            $row = $komaDB->fetchArray($result);
            $_SESSION['UserId'] = $row['uid'];
            $_SESSION['RoleId'] = $row['rid'];
            $_SESSION['UserName'] = $row['uname'];
            $_SESSION['Token'] = md5(time().$row['uname']);
            
            $komaDB->query("UPDATE ".$komaDB->prefix('users')." SET last_visit_date = ".time()." WHERE uid = '".$row['uid']."'");
            
            return true;
        }
        
        return false;
    }
    
    function logout($sid = '', $ksid = '')
    {
        if(isset($sid) && isset($ksid))
        {
            if($sid == $ksid)
            {
                $_SESSION = array();
                
                return true;
            }
        }
        
        return false;
    }
    
    static function getInstance()
    {
        return self::createInstance(__CLASS__);
    }
}
?>